package com.ptt.sqm.component;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.ksoap2.serialization.PropertyInfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.FragmentManager;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ptt.sqm.activity.MainActivity;
import com.ptt.sqm.activity.MakeAssessFragment;
import com.ptt.sqm.activity.ReportAssessFragment;
import com.ptt.sqm.activity.ReportScoreFragment;
import com.ptt.sqm.model.AssessItem;
import com.ptt.sqm.model.AssessItemList;
import com.ptt.sqm.model.AssessUserType;
import com.ptt.sqm.model.AssessUserTypeList;
import com.ptt.sqm.model.CycleAssess;
import com.ptt.sqm.model.CycleAssessList;
import com.ptt.sqm.model.Project;
import com.ptt.sqm.model.ProjectList;
import com.ptt.sqm.model.ScoreReportList;
import com.ptt.sqm.model.Station;
import com.ptt.sqm.model.StationList;
import com.ptt.sqm.model.SuggestionReport;
import com.ptt.sqm.model.SuggestionReportList;
import com.ptt.sqm.model.YearAssess;
import com.ptt.sqm.model.YearAssessList;
import com.ptt.sqm.model.ZoneAssess;
import com.ptt.sqm.model.ZoneAssessList;
import com.ptt.sqm.session.SessionManager;
import com.ptt.sqm.util.AppUtil;
import com.ptt.sqm.util.WidgetUtil;
import com.ptt.sqm.ws.AsyncResponse;
import com.ptt.sqm.ws.DecrementCallback;
import com.ptt.sqm.ws.DefaultTask;
import com.ptt.sqm.ws.WebserviceCall;
import com.ptt.sqmonmobile.R;

public class Search implements AsyncResponse, DecrementCallback {

	private static Search singleton;

	private Activity activity;
	private View view;
	private Gson gson;
	private int number;

	public YearAssessList years;
	public ProjectList projects;
	public CycleAssessList cycles;
	public ZoneAssessList zones;
	public StationList stations;
	public AssessUserTypeList types;

	// For Pending
	public YearAssessList yearsPending;
	public ProjectList projectsPending;
	public CycleAssessList cyclesPending;
	public StationList stationsPending;

	public String shipToSelected;
	public String shipNameSelected;
	public String locationSelected;

	// Create Webservice class object
	WebserviceCall com;
	private DefaultTask mTask = null;

	// Output
	private SuggestionReportList suggestRptList;
	private ScoreReportList scoreRptList;
	public AssessItemList assessItemList;

	// Loading
	private View mContentView;
	private View mProgressView;

	int cnt;

	private boolean isFirst = true;

	public static Search getInstance(Activity activity, View view, Gson gson, WebserviceCall com) {
		if (singleton == null) {
			singleton = new Search(activity, view, gson, com);
		}
		return singleton;
	}

	public Search(Activity activity, View view, Gson gson, WebserviceCall com) {
		// TODO Auto-generated constructor stub
		this.activity = activity;
		this.view = view;
		this.gson = gson;
		this.com = com;

		initialize();
	}

	private void initialize() {
		// TODO Auto-generated method stub
		setCount(10);

		mTask = new DefaultTask(com, activity.getString(R.string.method_listyear), Boolean.FALSE);
		mTask.delegate = this;
		mTask.execute();

		mTask = new DefaultTask(com, activity.getString(R.string.method_listproject), Boolean.FALSE);
		mTask.delegate = this;
		mTask.execute();

		mTask = new DefaultTask(com, activity.getString(R.string.method_listcycle), Boolean.FALSE);
		mTask.delegate = this;
		mTask.execute();

		mTask = new DefaultTask(com, activity.getString(R.string.method_listzone), Boolean.FALSE);
		mTask.delegate = this;
		mTask.execute();

		mTask = new DefaultTask(com, activity.getString(R.string.method_liststation), Boolean.FALSE);
		mTask.delegate = this;
		mTask.execute();

		mTask = new DefaultTask(com, activity.getString(R.string.method_listassessusertype), Boolean.FALSE);
		mTask.delegate = this;
		mTask.execute();

		// For Pending
		PropertyInfo pendingProp = new PropertyInfo();
		pendingProp.setName(AppUtil.PendingOnly);
		pendingProp.setValue(true);
		pendingProp.setType(Boolean.class);

		mTask = new DefaultTask(com, activity.getString(R.string.method_listyear), Boolean.TRUE);
		mTask.delegate = this;
		mTask.execute(pendingProp);

		mTask = new DefaultTask(com, activity.getString(R.string.method_listproject), Boolean.TRUE);
		mTask.delegate = this;
		mTask.execute(pendingProp);

		mTask = new DefaultTask(com, activity.getString(R.string.method_listcycle), Boolean.TRUE);
		mTask.delegate = this;
		mTask.execute(pendingProp);

		mTask = new DefaultTask(com, activity.getString(R.string.method_liststation), Boolean.TRUE);
		mTask.delegate = this;
		mTask.execute(pendingProp);
	}

	public static void reset() {
		singleton = null;
	}

	public void listStation() {
		isFirst = false;

		// All Stations
		List<Station> arr = new ArrayList<Station>();
		for (int index = 0; index < stations.Station.size(); index++) {
			arr.add(stations.Station.get(index));
		}

		StationAdapter arrAdt = new StationAdapter(activity, android.R.layout.simple_spinner_item, (ArrayList<Station>) arr);

		final AutoCompleteTextView autoComplete = (AutoCompleteTextView) view.findViewById(R.id.station);
		autoComplete.setAdapter(arrAdt);
		autoComplete.setThreshold(1);

		autoComplete.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				shipToSelected = ((Station) arg0.getItemAtPosition(arg2)).Ship_To;
				shipNameSelected = ((Station) arg0.getItemAtPosition(arg2)).Ship_To_Name;
			}
		});

		autoComplete.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				if (autoComplete.getText().toString().length() == 0) {
					autoComplete.showDropDown();
				}

				return false;
			}
		});

		autoComplete.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub

				if (autoComplete.getText().toString().length() == 0)
					autoComplete.showDropDown();
				return false;
			}

		});
	}

	public void listStationPending() {
		isFirst = false;

		// All Stations
		List<Station> arr = new ArrayList<Station>();
		for (int index = 0; index < stationsPending.Station.size(); index++) {
			arr.add(stationsPending.Station.get(index));
		}

		StationAdapter arrAdt = new StationAdapter(activity, android.R.layout.simple_spinner_item, (ArrayList<Station>) arr);

		final AutoCompleteTextView autoComplete = (AutoCompleteTextView) view.findViewById(R.id.station);
		autoComplete.setAdapter(arrAdt);
		autoComplete.setThreshold(1);

		autoComplete.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				shipToSelected = ((Station) arg0.getItemAtPosition(arg2)).Ship_To;
				shipNameSelected = ((Station) arg0.getItemAtPosition(arg2)).Ship_To_Name;
				locationSelected = ((Station) arg0.getItemAtPosition(arg2)).LOCATION_ID;
			}
		});

		autoComplete.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				if (autoComplete.getText().toString().length() == 0) {
					autoComplete.showDropDown();
				}

				return false;
			}
		});

		autoComplete.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub

				if (autoComplete.getText().toString().length() == 0)
					autoComplete.showDropDown();
				return false;
			}

		});
	}

	public void getListStation(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		try {
			if (((Boolean) objects[0]).booleanValue())
				stationsPending = (StationList) gson.fromJson((String) output, StationList.class);
			else
				stations = (StationList) gson.fromJson((String) output, StationList.class);

			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}

	}

	public void listZone() {
		// Set Div Spinner
		Spinner divSpinner = (Spinner) view.findViewById(R.id.div_assess);
		List<String> checkDup = new ArrayList<String>();
		List<SpinnerObject> arr = new ArrayList<SpinnerObject>();
		arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));
		for (int index = 0; index < zones.ZoneAssess.size(); index++) {
			String divId = ((ZoneAssess) zones.ZoneAssess.get(index)).DivId;
			String divName = ((ZoneAssess) zones.ZoneAssess.get(index)).DivName;

			if (!checkDup.contains(divId)) {
				arr.add(new SpinnerObject(divName, divId));
				checkDup.add(divId);
			}
		}
		checkDup.clear();
		ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
		arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		divSpinner.setAdapter(arrAdt);
	}

	public void getListZone(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			zones = (ZoneAssessList) gson.fromJson((String) output, ZoneAssessList.class);
			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}
	}

	public void getListCycle(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		try {
			if (((Boolean) objects[0]).booleanValue())
				cyclesPending = (CycleAssessList) gson.fromJson((String) output, CycleAssessList.class);
			else
				cycles = (CycleAssessList) gson.fromJson((String) output, CycleAssessList.class);
			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}
	}

	public void getListProject(String method, Object output, Object... objects) {
		try {
			if (((Boolean) objects[0]).booleanValue())
				projectsPending = (ProjectList) gson.fromJson((String) output, ProjectList.class);
			else
				projects = (ProjectList) gson.fromJson((String) output, ProjectList.class);
			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}
	}

	public void listYear() {
		// Set Year Spinner
		Spinner yearSpinner = (Spinner) view.findViewById(R.id.year_assess);
		List<String> checkDup = new ArrayList<String>();
		List<SpinnerObject> arr = new ArrayList<SpinnerObject>();
		arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));
		for (int index = 0; index < years.YearAssess.size(); index++) {
			String YearAssessId = ((YearAssess) years.YearAssess.get(index)).YearAssessId;
			String YearAssessName = ((YearAssess) years.YearAssess.get(index)).YearAssessName;

			if (!checkDup.contains(YearAssessId)) {
				arr.add(new SpinnerObject(YearAssessName, YearAssessId));
				checkDup.add(YearAssessId);
			}
		}
		checkDup.clear();
		ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
		arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		yearSpinner.setAdapter(arrAdt);

	}

	public void listYearPending() {
		// Set Year Spinner
		Spinner yearSpinner = (Spinner) view.findViewById(R.id.year_assess);
		List<String> checkDup = new ArrayList<String>();
		List<SpinnerObject> arr = new ArrayList<SpinnerObject>();
		arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));
		for (int index = 0; index < yearsPending.YearAssess.size(); index++) {
			String YearAssessId = ((YearAssess) yearsPending.YearAssess.get(index)).YearAssessId;
			String YearAssessName = ((YearAssess) yearsPending.YearAssess.get(index)).YearAssessName;

			if (!checkDup.contains(YearAssessId)) {
				arr.add(new SpinnerObject(YearAssessName, YearAssessId));
				checkDup.add(YearAssessId);
			}
		}
		checkDup.clear();
		ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
		arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		yearSpinner.setAdapter(arrAdt);

	}

	public void getListYear(String method, Object output, Object... objects) {
		try {
			if (((Boolean) objects[0]).booleanValue())
				yearsPending = (YearAssessList) gson.fromJson((String) output, YearAssessList.class);
			else
				years = (YearAssessList) gson.fromJson((String) output, YearAssessList.class);
			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}
	}

	public void listAssessUserType() {
		// Set UserType Spinner
		Spinner typeSpinner = (Spinner) view.findViewById(R.id.type_assess);
		List<String> checkDup = new ArrayList<String>();
		List<SpinnerObject> arr = new ArrayList<SpinnerObject>();
		arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));
		for (int index = 0; index < types.AssessUserType.size(); index++) {
			String AssessUserTypeId = ((AssessUserType) types.AssessUserType.get(index)).AssessUserTypeId;
			String AssessUserTypeName = ((AssessUserType) types.AssessUserType.get(index)).AssessUserTypeName;

			if (!checkDup.contains(AssessUserTypeId)) {
				arr.add(new SpinnerObject(AssessUserTypeName, AssessUserTypeId));
				checkDup.add(AssessUserTypeId);
			}
		}
		checkDup.clear();
		ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
		arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		typeSpinner.setAdapter(arrAdt);
	}

	public void getListAssessUserType(String method, Object output) {
		try {
			types = (AssessUserTypeList) gson.fromJson((String) output, AssessUserTypeList.class);
			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}

	}

	public void getYearFilter(int pos) {
		try {
			Spinner yearSpinner = (Spinner) view.findViewById(R.id.year_assess);
			Spinner projSpinner = (Spinner) view.findViewById(R.id.project_assess);
			Spinner cycleSpinner = (Spinner) view.findViewById(R.id.cycle_assess);
			List<String> checkDup = new ArrayList<String>();
			List<SpinnerObject> arr;

			// Clear Cycle
			if (cycleSpinner != null) {
				arr = new ArrayList<SpinnerObject>();
				arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));

				ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
				arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				cycleSpinner.setAdapter(arrAdt);
			}

			// Set Project
			if (projSpinner != null) {
				arr = new ArrayList<SpinnerObject>();
				arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));

				if (pos != 0) {
					for (int index = 0; index < projects.Project.size(); index++) {
						if (((SpinnerObject) yearSpinner.getSelectedItem()).getValue().equals(projects.Project.get(index).YearId)) {
							String ProjectId = ((Project) projects.Project.get(index)).ProjectId;
							String ProjectName = ((Project) projects.Project.get(index)).ProjectName;

							if (!checkDup.contains(ProjectId)) {
								arr.add(new SpinnerObject(ProjectName, ProjectId));
								checkDup.add(ProjectId);
							}
						}
					}
				}
				checkDup.clear();

				ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
				arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				projSpinner.setAdapter(arrAdt);
			}
		} catch (Exception e) {

		}
	}

	public void getYearFilterPending(int pos) {
		try {
			Spinner yearSpinner = (Spinner) view.findViewById(R.id.year_assess);
			Spinner projSpinner = (Spinner) view.findViewById(R.id.project_assess);
			Spinner cycleSpinner = (Spinner) view.findViewById(R.id.cycle_assess);
			List<String> checkDup = new ArrayList<String>();
			List<SpinnerObject> arr;

			// Clear Cycle
			if (cycleSpinner != null) {
				arr = new ArrayList<SpinnerObject>();
				arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));

				ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
				arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				cycleSpinner.setAdapter(arrAdt);
			}

			// Set Project
			if (projSpinner != null) {
				arr = new ArrayList<SpinnerObject>();
				arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));

				if (pos != 0) {
					for (int index = 0; index < projectsPending.Project.size(); index++) {
						if (((SpinnerObject) yearSpinner.getSelectedItem()).getValue().equals(projectsPending.Project.get(index).YearId)) {
							String ProjectId = ((Project) projectsPending.Project.get(index)).ProjectId;
							String ProjectName = ((Project) projectsPending.Project.get(index)).ProjectName;

							if (!checkDup.contains(ProjectId)) {
								arr.add(new SpinnerObject(ProjectName, ProjectId));
								checkDup.add(ProjectId);
							}
						}
					}
				}
				checkDup.clear();

				ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
				arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				projSpinner.setAdapter(arrAdt);
			}
		} catch (Exception e) {

		}
	}

	public void getProjectFilter(int pos) {
		try {
			Spinner projSpinner = (Spinner) view.findViewById(R.id.project_assess);
			Spinner cycleSpinner = (Spinner) view.findViewById(R.id.cycle_assess);
			List<String> checkDup = new ArrayList<String>();
			List<SpinnerObject> arr;

			// Set Cycle
			if (cycleSpinner != null) {
				arr = new ArrayList<SpinnerObject>();
				arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));

				if (pos != 0) {
					for (int index = 0; index < cycles.CycleAssess.size(); index++) {
						if (((SpinnerObject) projSpinner.getSelectedItem()).getValue().equals(cycles.CycleAssess.get(index).ProjectId)) {
							String CycleAssessId = ((CycleAssess) cycles.CycleAssess.get(index)).CycleAssessId;
							String Cycle = ((CycleAssess) cycles.CycleAssess.get(index)).Cycle;

							if (!checkDup.contains(CycleAssessId)) {
								arr.add(new SpinnerObject(Cycle, CycleAssessId, cycles.CycleAssess.get(index)));
								checkDup.add(CycleAssessId);
							}
						}
					}
				}
				checkDup.clear();

				ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
				arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				cycleSpinner.setAdapter(arrAdt);
			}

		} catch (Exception e) {

		}
	}

	public void getProjectFilterPending(int pos) {
		try {
			Spinner projSpinner = (Spinner) view.findViewById(R.id.project_assess);
			Spinner cycleSpinner = (Spinner) view.findViewById(R.id.cycle_assess);
			List<String> checkDup = new ArrayList<String>();
			List<SpinnerObject> arr;

			// Set Cycle
			if (cycleSpinner != null) {
				arr = new ArrayList<SpinnerObject>();
				arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));

				if (pos != 0) {
					for (int index = 0; index < cyclesPending.CycleAssess.size(); index++) {
						if (((SpinnerObject) projSpinner.getSelectedItem()).getValue().equals(cyclesPending.CycleAssess.get(index).ProjectId)) {
							String CycleAssessId = ((CycleAssess) cycles.CycleAssess.get(index)).CycleAssessId;
							String Cycle = ((CycleAssess) cyclesPending.CycleAssess.get(index)).Cycle;

							if (!checkDup.contains(CycleAssessId)) {
								arr.add(new SpinnerObject(Cycle, CycleAssessId, cyclesPending.CycleAssess.get(index)));
								checkDup.add(CycleAssessId);
							}
						}
					}
				}
				checkDup.clear();

				ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
				arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				cycleSpinner.setAdapter(arrAdt);
			}

		} catch (Exception e) {

		}
	}

	public void getDivFilter(int pos) {
		try {
			Spinner divSpinner = (Spinner) view.findViewById(R.id.div_assess);
			Spinner deptSpinner = (Spinner) view.findViewById(R.id.dept_assess);
			Spinner zonesSpinner = (Spinner) view.findViewById(R.id.zone_assess);
			List<String> checkDup = new ArrayList<String>();
			List<SpinnerObject> arr;

			// Clear Zones
			if (zonesSpinner != null) {
				arr = new ArrayList<SpinnerObject>();
				arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));

				ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
				arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				zonesSpinner.setAdapter(arrAdt);
			}

			// Set Dept
			if (deptSpinner != null) {
				arr = new ArrayList<SpinnerObject>();
				arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));

				if (pos != 0) {
					for (int index = 0; index < zones.ZoneAssess.size(); index++) {
						if (((SpinnerObject) divSpinner.getSelectedItem()).getValue().equals(zones.ZoneAssess.get(index).DivId)) {
							String deptId = ((ZoneAssess) zones.ZoneAssess.get(index)).DeptId;
							String deptName = ((ZoneAssess) zones.ZoneAssess.get(index)).DeptName;

							if (!checkDup.contains(deptId)) {
								arr.add(new SpinnerObject(deptName, deptId));
								checkDup.add(deptId);
							}
						}
					}
				}
				checkDup.clear();

				ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
				arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				deptSpinner.setAdapter(arrAdt);
			}

		} catch (Exception e) {
			Log.i("Div", e.getMessage());
		}
	}

	public void getDeptFilter(int pos) {
		try {
			Spinner divSpinner = (Spinner) view.findViewById(R.id.div_assess);
			Spinner deptSpinner = (Spinner) view.findViewById(R.id.dept_assess);
			Spinner zonesSpinner = (Spinner) view.findViewById(R.id.zone_assess);
			List<String> checkDup = new ArrayList<String>();
			List<SpinnerObject> arr;

			// Set Zone
			if (zonesSpinner != null) {
				arr = new ArrayList<SpinnerObject>();
				arr.add(new SpinnerObject(activity.getString(R.string.header_spinner), ""));

				if (pos != 0) {
					for (int index = 0; index < zones.ZoneAssess.size(); index++) {
						if (((SpinnerObject) deptSpinner.getSelectedItem()).getValue().equals(zones.ZoneAssess.get(index).DeptId)) {
							String zoneId = ((ZoneAssess) zones.ZoneAssess.get(index)).Zone_Id;
							String zoneName = ((ZoneAssess) zones.ZoneAssess.get(index)).Zone_Name;

							if (!checkDup.contains(zoneId)) {
								arr.add(new SpinnerObject(zoneName, zoneId));
								checkDup.add(zoneId);
							}
						}
					}
				}
				checkDup.clear();

				ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(activity, android.R.layout.simple_spinner_dropdown_item, arr);
				arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				zonesSpinner.setAdapter(arrAdt);
			}

		} catch (Exception e) {
			Log.i("Dept", e.getMessage());
		}
	}

	public void getZoneFilter(int pos) {
		// TODO Auto-generated method stub
		shipToSelected = "";
		final AutoCompleteTextView autoComplete = (AutoCompleteTextView) view.findViewById(R.id.station);
		autoComplete.setText(AppUtil.EMPTY);

		Spinner zonesSpinner = (Spinner) view.findViewById(R.id.zone_assess);
		Spinner deptSpinner = (Spinner) view.findViewById(R.id.dept_assess);
		Spinner divSpinner = (Spinner) view.findViewById(R.id.div_assess);
		List<Station> arr = new ArrayList<Station>();
		final Map<String, String> map = new TreeMap<String, String>();

		if (pos != 0) {
			for (int index = 0; index < stations.Station.size(); index++) {
				if (((SpinnerObject) zonesSpinner.getSelectedItem()).getValue().equals(stations.Station.get(index).Zone_ID)) {
					arr.add(stations.Station.get(index));
				}
			}

		} else if (!isFirst) {
			if (deptSpinner.getSelectedItemPosition() != 0) {
				for (int index = 0; index < stations.Station.size(); index++) {
					if (((SpinnerObject) deptSpinner.getSelectedItem()).getValue().equals(stations.Station.get(index).DeptId)) {
						arr.add(stations.Station.get(index));
					}
				}
			} else if (divSpinner.getSelectedItemPosition() != 0) {
				for (int index = 0; index < stations.Station.size(); index++) {
					if (((SpinnerObject) divSpinner.getSelectedItem()).getValue().equals(stations.Station.get(index).DivId)) {
						arr.add(stations.Station.get(index));
					}
				}
			} else {
				for (int index = 0; index < stations.Station.size(); index++) {
					arr.add(stations.Station.get(index));
				}
			}
		} else {
			return;
		}

		StationAdapter arrAdt = new StationAdapter(activity, android.R.layout.simple_spinner_item, (ArrayList<Station>) arr);

		autoComplete.setAdapter(arrAdt);
		autoComplete.setThreshold(1);
		autoComplete.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				shipToSelected = ((Station) arg0.getItemAtPosition(arg2)).Ship_To;
				shipNameSelected = ((Station) arg0.getItemAtPosition(arg2)).Ship_To_Name;

			}
		});
	}

	public void getZoneFilterPending(int pos) {
		// TODO Auto-generated method stub
		shipToSelected = "";
		final AutoCompleteTextView autoComplete = (AutoCompleteTextView) view.findViewById(R.id.station);
		autoComplete.setText(AppUtil.EMPTY);

		Spinner zonesSpinner = (Spinner) view.findViewById(R.id.zone_assess);
		Spinner deptSpinner = (Spinner) view.findViewById(R.id.dept_assess);
		Spinner divSpinner = (Spinner) view.findViewById(R.id.div_assess);
		List<Station> arr = new ArrayList<Station>();
		final Map<String, String> map = new TreeMap<String, String>();

		if (pos != 0) {
			for (int index = 0; index < stationsPending.Station.size(); index++) {
				if (((SpinnerObject) zonesSpinner.getSelectedItem()).getValue().equals(stationsPending.Station.get(index).Zone_ID)) {
					arr.add(stationsPending.Station.get(index));
				}
			}

		} else if (!isFirst) {
			if (deptSpinner.getSelectedItemPosition() != 0) {
				for (int index = 0; index < stationsPending.Station.size(); index++) {
					if (((SpinnerObject) deptSpinner.getSelectedItem()).getValue().equals(stationsPending.Station.get(index).DeptId)) {
						arr.add(stationsPending.Station.get(index));
					}
				}
			} else if (divSpinner.getSelectedItemPosition() != 0) {
				for (int index = 0; index < stationsPending.Station.size(); index++) {
					if (((SpinnerObject) divSpinner.getSelectedItem()).getValue().equals(stationsPending.Station.get(index).DivId)) {
						arr.add(stationsPending.Station.get(index));
					}
				}
			} else {
				for (int index = 0; index < stationsPending.Station.size(); index++) {
					arr.add(stationsPending.Station.get(index));
				}
			}
		} else {
			return;
		}

		StationAdapter arrAdt = new StationAdapter(activity, android.R.layout.simple_spinner_item, (ArrayList<Station>) arr);

		autoComplete.setAdapter(arrAdt);
		autoComplete.setThreshold(1);
		autoComplete.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				shipToSelected = ((Station) arg0.getItemAtPosition(arg2)).Ship_To;
				shipNameSelected = ((Station) arg0.getItemAtPosition(arg2)).Ship_To_Name;
				locationSelected = ((Station) arg0.getItemAtPosition(arg2)).LOCATION_ID;

			}
		});
	}

	public void showSearchForMake(Activity activity, View view) {
		this.activity = activity;
		this.view = view;
		listYearPending();

		listZone();

		listStationPending();

		final Spinner yearSpin = (Spinner) view.findViewById(R.id.year_assess);
		final Spinner projSpin = (Spinner) view.findViewById(R.id.project_assess);
		final Spinner cycleSpin = (Spinner) view.findViewById(R.id.cycle_assess);
		final Spinner divSpin = (Spinner) view.findViewById(R.id.div_assess);
		final Spinner deptSpin = (Spinner) view.findViewById(R.id.dept_assess);
		final Spinner zoneSpin = (Spinner) view.findViewById(R.id.zone_assess);
		final AutoCompleteTextView stationAuto = (AutoCompleteTextView) view.findViewById(R.id.station);

		yearSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				validateYear();
				getYearFilterPending(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		projSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				validateProject();
				getProjectFilterPending(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		cycleSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				validateCycle();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		divSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getDivFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		deptSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getDeptFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		zoneSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getZoneFilterPending(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		stationAuto.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				validateStation(s.length());
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub

			}
		});

	}

	protected void validateStation(int length) {
		// TODO Auto-generated method stub
		TextView stationAlert = (TextView) view.findViewById(R.id.station_alert);
		if (stationAlert != null)
			if (length == 0) {
				stationAlert.setError(activity.getString(R.string.alert_required_field));
				// stationAlert.requestFocus();
			} else {
				stationAlert.setError(null);
			}
	}

	protected void validateCycle() {
		// TODO Auto-generated method stub
		Spinner cycleSpin = (Spinner) view.findViewById(R.id.cycle_assess);
		TextView cycleAlert = (TextView) view.findViewById(R.id.cycle_alert);
		if (cycleAlert != null)
			if (cycleSpin.getSelectedItemPosition() == 0) {
				cycleAlert.setError(activity.getString(R.string.alert_required_field));
				// cycleAlert.requestFocus();
			} else {
				cycleAlert.setError(null);
			}
	}

	protected void validateProject() {
		// TODO Auto-generated method stub
		Spinner projSpin = (Spinner) view.findViewById(R.id.project_assess);
		TextView projAlert = (TextView) view.findViewById(R.id.project_alert);
		if (projAlert != null)
			if (projSpin.getSelectedItemPosition() == 0) {
				projAlert.setError(activity.getString(R.string.alert_required_field));
				// projAlert.requestFocus();
			} else {
				projAlert.setError(null);
			}
	}

	protected void validateYear() {
		// TODO Auto-generated method stub
		Spinner yearSpin = (Spinner) view.findViewById(R.id.year_assess);
		TextView yearAlert = (TextView) view.findViewById(R.id.year_alert);
		if (yearAlert != null)
			if (yearSpin.getSelectedItemPosition() == 0) {
				yearAlert.setError(activity.getString(R.string.alert_required_field));
				// yearAlert.requestFocus();
			} else {
				yearAlert.setError(null);
			}
	}

	public void showSearchForReport(Activity activity, View view) {
		this.activity = activity;
		this.view = view;
		listYear();

		listZone();

		listStation();

		listAssessUserType();

		final Spinner yearSpin = (Spinner) view.findViewById(R.id.year_assess);
		final Spinner projSpin = (Spinner) view.findViewById(R.id.project_assess);
		final Spinner cycleSpin = (Spinner) view.findViewById(R.id.cycle_assess);
		final Spinner divSpin = (Spinner) view.findViewById(R.id.div_assess);
		final Spinner deptSpin = (Spinner) view.findViewById(R.id.dept_assess);
		final Spinner zoneSpin = (Spinner) view.findViewById(R.id.zone_assess);
		final Spinner typeSpin = (Spinner) view.findViewById(R.id.type_assess);

		yearSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				getYearFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		projSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				getProjectFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		divSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getDivFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		deptSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getDeptFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		zoneSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getZoneFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

	}

	public void showSearchStation(Activity activity, View view) {
		this.activity = activity;
		this.view = view;

		listZone();

		listStation();

		final Spinner divSpin = (Spinner) view.findViewById(R.id.div_assess);
		final Spinner deptSpin = (Spinner) view.findViewById(R.id.dept_assess);
		final Spinner zoneSpin = (Spinner) view.findViewById(R.id.zone_assess);
		final AutoCompleteTextView stationAuto = (AutoCompleteTextView) view.findViewById(R.id.station);

		divSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getDivFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		deptSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getDeptFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		zoneSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getZoneFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		stationAuto.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				validateStation(s.length());
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub

			}
		});

	}

	public void showSearchAssess(Activity activity, View view) {
		this.activity = activity;
		this.view = view;
		listYear();

		listZone();

		listStation();

		final Spinner yearSpin = (Spinner) view.findViewById(R.id.year_assess);
		final Spinner projSpin = (Spinner) view.findViewById(R.id.project_assess);
		final Spinner cycleSpin = (Spinner) view.findViewById(R.id.cycle_assess);
		final Spinner divSpin = (Spinner) view.findViewById(R.id.div_assess);
		final Spinner deptSpin = (Spinner) view.findViewById(R.id.dept_assess);
		final Spinner zoneSpin = (Spinner) view.findViewById(R.id.zone_assess);
		final EditText startDate = (EditText) view.findViewById(R.id.start_assess_date);
		final EditText endDate = (EditText) view.findViewById(R.id.end_assess_date);

		yearSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				getYearFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		projSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				getProjectFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		divSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getDivFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		deptSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getDeptFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		zoneSpin.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				// TODO Auto-generated method stub
				getZoneFilter(pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		startDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// To show current date in the datepicker
				Calendar mcurrentDate = Calendar.getInstance();
				int mYear = mcurrentDate.get(Calendar.YEAR);
				int mMonth = mcurrentDate.get(Calendar.MONTH);
				int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
				DatePickerDialog mDatePicker = new DatePickerDialog(v.getContext(), new OnDateSetListener() {
					public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
						// TODO Auto-generated method stub
						Calendar mSetDate = Calendar.getInstance();
						mSetDate.set(Calendar.YEAR, AppUtil.convertYearTH(selectedyear));
						mSetDate.set(Calendar.MONTH, selectedmonth);
						mSetDate.set(Calendar.DAY_OF_MONTH, selectedday);
						startDate.setText(AppUtil.formatter_TH_SEARCH.format(mSetDate.getTime()));
					}
				}, mYear, mMonth, mDay);
				mDatePicker.setTitle("Select date");
				mDatePicker.show();
			}

		});

		endDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// To show current date in the datepicker
				Calendar mcurrentDate = Calendar.getInstance();
				int mYear = mcurrentDate.get(Calendar.YEAR);
				int mMonth = mcurrentDate.get(Calendar.MONTH);
				int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
				DatePickerDialog mDatePicker = new DatePickerDialog(v.getContext(), new OnDateSetListener() {
					public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
						// TODO Auto-generated method stub
						Calendar mSetDate = Calendar.getInstance();
						mSetDate.set(Calendar.YEAR, AppUtil.convertYearTH(selectedyear));
						mSetDate.set(Calendar.MONTH, selectedmonth);
						mSetDate.set(Calendar.DAY_OF_MONTH, selectedday);
						endDate.setText(AppUtil.formatter_TH_SEARCH.format(mSetDate.getTime()));
					}
				}, mYear, mMonth, mDay);
				mDatePicker.setTitle("Select date");
				mDatePicker.show();
			}

		});
	}

	@Override
	public void processFinish(String method, Object output) {
		// TODO Auto-generated method stub
	}

	@Override
	public void processFinish(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		try {
			if (method.equals(activity.getString(R.string.method_listyear)))
				getListYear(method, output, objects);
			else if (method.equals(activity.getString(R.string.method_listproject)))
				getListProject(method, output, objects);
			else if (method.equals(activity.getString(R.string.method_listcycle)))
				getListCycle(method, output, objects);
			else if (method.equals(activity.getString(R.string.method_listzone)))
				getListZone(method, output);
			else if (method.equals(activity.getString(R.string.method_liststation)))
				getListStation(method, output, objects);
			else if (method.equals(activity.getString(R.string.method_listassessusertype)))
				getListAssessUserType(method, output);
		} catch (Exception e) {
		}

		onDecrementCount();
	}

	@Override
	public void setCount(int cnt) {
		this.cnt = cnt;
	}

	@Override
	public void onDecrementCount() {
		cnt--;
		if (cnt <= 0) {
			try {
				if (years != null && projects != null && cycles != null && zones != null && stations != null && types != null && yearsPending != null && projectsPending != null
					&& cyclesPending != null && stationsPending != null) {

					Intent it = new Intent(activity, MainActivity.class);
					activity.startActivity(it);
				} else {
					SessionManager session = new SessionManager(activity.getApplicationContext(), activity);
					session.logoutUserWithError();
				}
			} catch (Exception e) {
				Toast.makeText(activity, e.toString(), Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	public void onDecrementCount(View view, int cnt) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDecrementCount(boolean flag) {
		// TODO Auto-generated method stub
		
	}

}
